package com.lw.leetcode.tree.b;

import com.lw.leetcode.tree.TreeNode;

/**
 * 814. 二叉树剪枝
 * 剑指 Offer II 047. 二叉树剪枝
 *
 * @Author liw
 * @Date 2021/6/21 14:48
 * @Version 1.0
 */
public class PruneTree {

    public TreeNode pruneTree(TreeNode root) {
        if (root == null) {
            return root;
        }
        find(root);
        if (root.val == 0 && root.left == null && root.right == null) {
            return null;
        }
        return root;
    }

    private boolean find(TreeNode node) {
        if (node == null) {
            return true;
        }
        boolean b1 = find(node.left);
        if (b1) {
            node.left = null;
        }
        boolean b2 = find(node.right);
        if (b2) {
            node.right = null;
        }
        return node.val == 0 && b1 && b2;
    }
}
